
package com.open.chat.server.command;

import org.jim.core.ImChannelContext;
import org.jim.core.ImConst;
import org.jim.core.ImPacket;
import org.jim.core.exception.ImException;
import org.jim.core.http.HttpRequest;
import org.jim.core.packets.AuthReqBody;
import org.jim.core.packets.Command;
import org.jim.core.utils.JsonKit;
import org.jim.server.JimServerAPI;
import org.jim.server.command.CommandManager;
import org.jim.server.command.handler.AuthReqHandler;
import org.jim.server.processor.handshake.WsHandshakeProcessor;

/**
 * 1.鉴权
 * 2.绑定自己、所在组
 * @author lets
 *
 */
public class TokenWsHandshakeProcessor extends WsHandshakeProcessor {

	@Override
	public void onAfterHandshake(ImPacket packet, ImChannelContext imChannelContext) throws ImException {
		
		AuthReqHandler  authReqHandler = (AuthReqHandler)CommandManager.getCommand(Command.COMMAND_AUTH_REQ);
		
		HttpRequest request = (HttpRequest)packet;
		String token = request.getParams().get("token") == null ? null : (String)request.getParams().get("token")[0];
		
		AuthReqBody  authReqBody = new AuthReqBody();
		authReqBody.setToken(token);
		
		byte[] loginBytes = JsonKit.toJsonBytes(authReqBody);
		request.setBody(loginBytes);
		try{
			request.setBodyString(new String(loginBytes, ImConst.CHARSET));
		}catch (Exception e){
			throw new ImException(e);
		}
		
		//鉴权在这里
		ImPacket loginRespPacket = authReqHandler.handler(request, imChannelContext);
		if(loginRespPacket != null){
			JimServerAPI.send(imChannelContext, loginRespPacket);
		}
	}
}
